package com.youxin.chat.pay.service.channel.impl.ypl.util;

import com.youxin.chat.pay.utils.RSAUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;

public class YplSignUtil {


    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;


    private static Logger logger = LoggerFactory.getLogger(YplSignUtil.class);

    public static String buildSign(String data, String priKey) {
        //String data  = JSONObject.toJSONString(object);
        System.out.println(data);
        String sign = null;
        try {
           // priKeyPath = "D:\\test\\ypl\\efps.pfx";
            PrivateKey privateKey = RSAUtils.loadPrivateKey(priKey);
            sign = Base64.encodeBase64String(RSAUtils.doSignature256((String)data, privateKey, "utf-8"));
        } catch (Exception e) {

            throw new RuntimeException("YPL加签失败");
        }
        return sign;
    }



    public static boolean verify(String data, String pubKeyPath, String sign) {
        logger.info("data={}",data);
        try {
            PublicKey publicKey = RSAUtils.loadPubKeyByStr(pubKeyPath);
            return RSAUtils.verfy(Base64.decodeBase64(sign), data.getBytes(), "SHA256withRSA", publicKey);
        } catch (Exception e) {
            throw new RuntimeException("YPL解签失败");
        }
    }

    /**
     * <p>
     * 公钥加密
     * </p>
     *
     * @param
     *
     * @param
     *
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String str, String pubKey) {

        byte[] data = str.getBytes();
        ByteArrayOutputStream out = new ByteArrayOutputStream();


        String result = "";
        try
        {
            PublicKey publicK = RSAUtils.loadPubKeyByStr(pubKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);

            int inputLen = data.length;
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
//			result = Base64Utils.encode(encryptedData);
            result = java.util.Base64.getEncoder().encodeToString(encryptedData);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;


    }

}
